package com.demo.cms.action.manage;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.springframework.context.i18n.LocaleContextHolder;

import com.demo.Constants;
import com.demo.cms.model.Article;
import com.demo.cms.model.Category;
import com.demo.cms.model.Channel;
import com.demo.cms.service.ArticleService;
import com.demo.cms.service.CategoryService;
import com.demo.cms.service.ChannelService;
import com.demo.core.dao.base.support.ResultSearchResult;
import com.demo.core.dao.base.support.SearchArgumentSupport;
import com.demo.core.model.Config;
import com.demo.core.model.Form;
import com.demo.core.model.FormItem;
import com.demo.core.model.Site;
import com.demo.core.model.Template;
import com.demo.core.model.support.AdjacencyListModel;
import com.demo.core.service.base.ConfigService;
import com.demo.core.service.base.FormService;
import com.demo.core.service.base.TemplateService;
import com.demo.core.util.collection.JsonUtils;
import com.demo.security.annotation.function.Function;
import com.demo.webapp.action.PageAction;
import com.demo.webapp.action.TemplateProvider;
import com.demo.webapp.context.MultisiteContextHolder;
import com.opensymphony.xwork2.interceptor.annotations.InputConfig;

/**
 * 后台管理的文章管理功能
 * @author ryuu.kk
 *
 */
@Function(id = 104200, pid = 10, code = "manage.article")
public class ArticleAction extends PageAction implements TemplateProvider {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 频道ID
	 */
	private Long channelId;
	
	/**
	 * 文章ID
	 */
	private Long id;
	
	/**
	 * 自定义表单ID-文章的类型字段值
	 */
	private String formId;
	
	/**
	 * 自定义表单模型,文章的字段选取由标点决定
	 */
	private Form form;
	
	/**
	 * 栏目ID
	 */
	private Long categoryId;
	
	/**
	 * 栏目父级ID
	 */
	private Long pid;
	
	/**
	 * json字符串
	 */
	private String json;
	
	/**
	 * 文章列表
	 */
	private List<Article> articleList;
	
	/**
	 * 文章模型
	 */
	private Article article;
	
	/**
	 * 栏目树
	 */
	private AdjacencyListModel tree;
	
	/**
	 * 栏目列表
	 */
	private List<Category> categoryList;
	
	/**
	 * 频道列表
	 */
	private List<Channel> channelList;
	
	/**
	 * 模板列表
	 */
	private List<Template> templateList;
	
	/**
	 * 文章访问服务
	 */
	private ArticleService articleService;
	
	/**
	 * 栏目访问服务
	 */
	private CategoryService categoryService;
	
	/**
	 * 模板服务
	 */
	private TemplateService templateService;
	
	/**
	 * 配置服务
	 */
	private ConfigService configService;
	
	/**
	 * 频道服务
	 */
	private ChannelService channelService;
	
	/**
	 * 自定义表单服务
	 */
	private FormService formService;
	
	/**
	 * 模板
	 */
	private Template template;
	
	/**
	 * 国际化配置
	 */
	private Config configI18N;
	
	/**
	 * 文章类型配置
	 */
	private Config configType;
	
	/**
	 * 取得文章列表
	 * 通过栏目ID查询文章列表
	 * @return resultMap
	 */
	@Function(id = 104210, pid = 104200, code = "manage.article.list")
	public String list() {
		// 取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
				
		//取得当前语言
		String i18n = LocaleContextHolder.getLocale().toString();
		if (log.isDebugEnabled()) {
			log.debug("Current-Language is " + i18n);
		}
		
		// 取得语言配置
		this.configI18N = configService.query(site.getId(), Constants.CONFIG_I18N);
		
		// 取得频道列表(用于选择切换频道)
		this.channelList = channelService.findList(siteId);
		// 默认使用第一个频道(默认频道)
		if (channelId == null && channelList.size() > 0) {
			channelId = channelList.get(0).getId();
		}
		
		if (categoryId == null) {
			Category category = categoryService.findRoot(channelId);
			if (category != null) {
				categoryId = category.getId();
			}
		}
		
		// 生成栏目树
		//tree();
		
		//TODO:修改i8n
		//articleList = articleService.findList(categoryId, "zh_CN");
		SearchArgumentSupport args = getArgumentSupport();
		ResultSearchResult<Article> result = null;
		
		if (categoryId == null) {
			// 频道不存在栏目时,增加提示信息
			String url = getRequest().getContextPath() + "/manage/Category_list.action?channelId=" + channelId;
			url = getResponse().encodeRedirectURL(url);
			String format = "该频道还没有创建栏目,请点击<a href='%s' style='font-size:14px;color:#B50000;'><strong> 这里 </strong></a>创建.";
			addActionMessage(String.format(format, url));
			return SUCCESS;
		}
		if (article == null) {
			// 使用任何配置的语言
			result = articleService.search(categoryId, "", args);
		} else {
			// 使用检索后的内容
			result = articleService.search(categoryId, 
											article.isComment(), 
											article.isDraft(),
											article.isCheck(),
											article.isPermission(),
											article.isEnabled(),
											"", args);
		}
		this.setResultSupport(result);
		articleList = new ArrayList<Article>(result.getResults());
		return SUCCESS;
	}
	
	/**
	 * 文章类型选择
	 * @return String
	 */
	public String chose() {
		
		Site site = getSite();
		// 取得文章类型列表
		this.configType = configService.query(site.getId(), Constants.CONFIG_ARTICLE_TYPE);
		
		return SUCCESS;
	}
	
	/**
	 * 文章创建页
	 * @return resultMap
	 */
	@Function(id = 104220, pid = 104200, code = "manage.article.create")
	public String create() {
		// 得到当前访问的站点
		Site site = getSite();
		// 取得语言配置
		this.configI18N = configService.query(site.getId(), Constants.CONFIG_I18N);
		
		// 如果没有选择类型,使用默认字段作为自定义表单ID
		if (formId == null) {
			// 取得文章类型列表
			this.configType = configService.query(site.getId(), Constants.CONFIG_ARTICLE_TYPE);
			if (configType != null && configType.getConfigItemList().size() > 0) {
				// 取得自定义表单ID
				formId = configType.getConfigItemList().get(0).getValue();
				// 取得表单模型
				this.form = formService.queryForm(Long.parseLong(formId));
			}
		}  else {
			this.form = formService.queryForm(Long.parseLong(formId));
		}
		this.categoryList = getCategory();
		this.templateList = getTemplate();
		if (categoryList == null) {
			return INPUT;
		}
		return SUCCESS;
	}
	
	/**
	 * 提交文章页
	 * @return resultMap
	 */
	@InputConfig(resultName="input")
	@Function(id = 104230, pid = 104200, code = "manage.article.save")
	public String save() {
		
		Long siteId = super.getSite().getId();
		article.setSiteId(siteId);
		articleService.save(article);
		//System.out.println(article);
		//System.out.println(articleContent);
		//articleService.save(article);
		addActionMessage(getText("article.added", "文章创建成功.", article.getShortTitle()));
		return CALLBACK;
	}
	
	/**
	 * 文章编辑页面
	 * @return resultMap
	 */
	@Function(id = 104240, pid = 104200, code = "manage.article.edit")
	public String edit() {
		// 得到当前访问的站点
		Site site = getSite();
		// 取得语言配置
		this.configI18N = configService.query(site.getId(), Constants.CONFIG_I18N);
		
		// 取得文章类型列表
		this.configType = configService.query(site.getId(), Constants.CONFIG_ARTICLE_TYPE);
		
		// 取得文章单页模板
		this.templateList = getTemplate();
		// 包含文章内容,使用query方法
		this.article = articleService.query(id);
		
		// 如果没有选择类型,使用文章类型字段作为自定义表单ID
		if (formId == null) {
			formId = article.getType();
		} 
		if (formId != null) {
			this.form = formService.queryForm(Long.parseLong(formId));
		}
		// 设置文章类型
		//article.setType(String.valueOf(formId));
		
		this.categoryList = getCategory();
		return SUCCESS;
	}
	
	/**
	 * 文章更新操作
	 * 文章更新后,跳转到原始页面(backurl)
	 * @return backurl页
	 */
	@Function(id = 104250, pid = 104200, code = "manage.article.update")
	public String update() {
		// 更新文章信息
		articleService.update(id, article);
		this.categoryList = getCategory();
		this.addActionMessage(this.getText("article.updated", "文章更新成功", article.getShortTitle()));
		return CALLBACK;
	}
	
	/**
	 * 文章删除
	 * @return backurl页
	 */
	@Function(id = 104260, pid = 104200, code = "manage.article.delete")
	public String delete() {
		
		articleService.delete(id);
		this.addActionMessage(this.getText("article.deleted", "文章已删除."));
		
		return CALLBACK;
	}
	
	/**
	 * 文章缩略图生成页面
	 * @return String
	 */
	public String thumb() {
		
		return SUCCESS;
	}
	
	/**
	 * 预览文章内容
	 * @return String
	 */
	public String review() {
		
		// 取得渲染模板
		template = templateService.find(article.getTemplateId());
		
		return "selfRender";
	}
	
	/**
	 * 查询所有栏目
	 * @return resultMap
	 */
	public String tree() {
		// 取得站点ID
		Site site = MultisiteContextHolder.getSite();
		Long siteId = site.getId();
		
		if(channelId == null) {
			// 取得频道列表
			this.channelList = channelService.findList(siteId);
			// 设置默认频道ID
			if (channelId == null && channelList.size() > 0) {
				channelId = channelList.get(0).getId();
			}
		}

		tree = categoryService.queryRootTree(channelId);
		// 生成json树
		json = JsonUtils.zTree(tree, true);
		return SUCCESS;
	}
	
	// ~~ private method ===================================================
	
	/**
	 * 取的当前站点所设置的栏目列表
	 * @return 标志
	 */
	private List<Category> getCategory() {
		Site site = MultisiteContextHolder.getSite();
		Locale locale = LocaleContextHolder.getLocale();
		if (site == null || locale == null) {
			return null;
		}
		Long siteId = site.getId();
		if (channelId == null) {
			List<Channel> channelList = channelService.findList(siteId);
			if (channelList.size() > 0) {
				channelId = channelList.get(0).getId();
			}
		}
		// 使用频道下的栏目信息,替换原始由站点下的所有栏目
		//List<Category> categoryList = categoryService.findAll(siteId, locale.toString());
		List<Category> categoryList = categoryService.findList(channelId, locale.toString());
		return categoryList;
	}
	
	private List<Template> getTemplate() {
		Site site = MultisiteContextHolder.getSite();
		if (site == null) {
			return null;
		}
		Long siteId = site.getId();
		// 取得文章模板列表, 不包含模板内容
		return templateService.findList(siteId, Constants.TYPE_ARTICLE, false);
	}
	
	/**
	 * 取得指定表单项
	 * 判断指定列是否需要被显示和显示样式等定义
	 * @param column 页面显示内容名
	 * @return 自定义表单项
	 */
	public FormItem getItem(String column) {
		if (this.form != null) {
			List<FormItem> formItemList = form.getFormItemList();
			if (formItemList != null) {
				for (FormItem item : formItemList) {
					if (item.getName().equals(column)) {
						return item;
					}
				}
			}
		}
		// 不存在默认未显示
		FormItem item = new FormItem();
		item.setEnabled(true);
		item.setName(column);
		item.setTitle(column);
		return item;
	}
	//~~~ getting,setting method ===================================================
	
	public Long getPid() {
		return pid;
	}

	public void setPid(Long pid) {
		this.pid = pid;
	}
	
	public Long getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(Long categoryId) {
		this.categoryId = categoryId;
	}

	public List<Article> getArticleList() {
		return articleList;
	}

	public Article getArticle() {
		return article;
	}

	public void setArticle(Article article) {
		this.article = article;
	}

	public void setArticleService(ArticleService articleService) {
		this.articleService = articleService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public void setFormService(FormService formService) {
		this.formService = formService;
	}

	public List<Category> getCategoryList() {
		return categoryList;
	}

	public void setChannelId(Long channelId) {
		this.channelId = channelId;
	}

	public Long getChannelId() {
		return channelId;
	}


	public List<Channel> getChannelList() {
		return channelList;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getFormId() {
		return formId;
	}

	public void setFormId(String formId) {
		this.formId = formId;
	}

	public Form getForm() {
		return form;
	}

	public void setForm(Form form) {
		this.form = form;
	}

	public List<Template> getTemplateList() {
		return templateList;
	}
	
	public AdjacencyListModel getTree() {
		return tree;
	}

	public Config getConfigI18N() {
		return configI18N;
	}
	
	public Config getConfigType() {
		return configType;
	}
	
	public String getJson() {
		return json;
	}

	public void setTemplateService(TemplateService templateService) {
		this.templateService = templateService;
	}

	public void setConfigService(ConfigService configService) {
		this.configService = configService;
	}

	public void setChannelService(ChannelService channelService) {
		this.channelService = channelService;
	}

	@Override
	public Template getTemplateModel() {
		return this.template;
	}
}
